package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	_ "net/http/pprof"
	"time"
)

// 消息结构体
type JSONData struct {
	Receiver     string       `json:"receiver"`
	Status       string       `json:"status"`
	Alerts       []Alerts     `json:"alerts"`
	CommonLabels CommonLabels `json:"commonLabels"`
	ExternalURL  string       `json:"externalURL"`
}
type Labels struct {
	Alertname   string `json:"alertname"`
	Instance    string `json:"instance"`
	Project     string `json:"project"`
	Severity    string `json:"severity"`
	Env         string `json:"env"`
	Application string `json:"application"`
}
type Alerts struct {
	Status      string      `json:"status"`
	Labels      Labels      `json:"labels"`
	StartsAt    string      `json:"startsAt"`
	EndsAt      string      `json:"endsAt"`
	Fingerprint string      `json:"fingerprint"`
	Annotations Annotations `json:"annotations"`
}
type Annotations struct {
	Description string `json:"description"`
	Summary     string `json:"summary"`
}

type CommonLabels struct {
	Alertname string `json:"alertname"`
}

// 微信消息体
type WxMsg struct {
	Msgtype string `json:"msgtype"`
	Text    Text   `json:"text"`
}
type Text struct {
	Content             string   `json:"content"`
	MentionedList       []string `json:"mentioned_list"`
	MentionedMobileList []string `json:"mentioned_mobile_list"`
}

func timetransfor(timeStr string) string {
	t, err := time.Parse(time.RFC3339, timeStr)
	if err != nil {
		fmt.Println("解析时间失败:", err)

	}
	// 获取东八区的位置

	loc, _ := time.LoadLocation("Asia/Shanghai")
	// 将UTC时间转换为东八区时间

	localTime := t.In(loc)
	fmt.Println("东八区时间:", localTime)
	str := fmt.Sprintf("%s", localTime.Format("2006-01-02 15:04:05"))
	return str
}

func main() {
	var xinwxrl string

	//请求header
	var headers []map[string]string
	var header = make(map[string]string, 1)
	header["Content-Type"] = "application/json"
	headers = append(headers, header)
	//企业微信机器人webhook
	//告警消息结构体
	var j JSONData

	gin.DisableConsoleColor()

	r := gin.Default()

	r.POST("/webhook/weixin/:param", func(c *gin.Context) {
		param := c.Param("param")
		fmt.Println("Received POST request with param:", param)
		xinwxrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + param
		res, err := c.GetRawData()
		if err != nil {
			log.Fatal("获取请求体失败:", err)
		}
		currentTime := time.Now()
		fmt.Println(currentTime.Format("2006-01-02 15:04:05"), "---请求的数据体是", string(res))
		err = json.Unmarshal(res, &j)

		//
		strartTime := timetransfor(j.Alerts[0].StartsAt)
		stopTime := timetransfor(j.Alerts[0].EndsAt)

		var alert_msg string
		for i, _ := range j.Alerts {
			if j.Alerts[i].Status == "resolved" {
				alert_msg = "<font color=\"info\"> 【鲁班平台-" + j.Alerts[0].Labels.Project + "-项目" + "告警结束" + "-】 </font>\n" +
					">应用名称：<font color=\"comment\"> " + j.Alerts[0].Labels.Application + "</font>\n" +
					">告警级别：<font color=\"comment\">" + j.Alerts[0].Labels.Severity + "</font>\n" +
					">告警类型：<font color=\"comment\"> " + j.Alerts[0].Labels.Alertname + "</font>\n" +
					">告警主机：<font color=\"comment\"> " + j.Alerts[0].Labels.Instance + "</font>\n" +
					">告警主题：<font color=\"comment\">" + j.Alerts[0].Annotations.Summary + "</font>\n" +
					">告警详情：<font color=\"comment\">" + j.Alerts[0].Annotations.Description + "</font>\n" +
					">告警环境：<font color=\"comment\"> " + j.Alerts[0].Labels.Env + "</font>\n" +
					">触发时间：<font color=\"comment\">" + strartTime + "</font>\n" +
					">结束时间：<font color=\"comment\">" + stopTime + "</font>\n"
			} else {
				alert_msg = "<font color=\"red\"> 【鲁班平台-" + j.Alerts[0].Labels.Project + "-项目" + "告警开始" + "-】 </font>\n" +
					">应用名称：<font color=\"comment\">" + j.Alerts[0].Labels.Application + "</font>\n" +
					">告警级别：<font color=\"comment\">" + j.Alerts[0].Labels.Severity + "</font>\n" +
					">告警类型：<font color=\"comment\"> " + j.Alerts[0].Labels.Alertname + "</font>\n" +
					">告警主机：<font color=\"warning\"> " + j.Alerts[0].Labels.Instance + "</font>\n" +
					">告警主题：<font color=\"comment\">" + j.Alerts[0].Annotations.Summary + "</font>\n" +
					">告警详情：<font color=\"comment\">" + j.Alerts[0].Annotations.Description + "</font>\n" +
					">告警环境：<font color=\"comment\">" + j.Alerts[0].Labels.Env + "</font>\n" +
					">触发时间：<font color=\"comment\">" + strartTime + "</font>\n"

			}

			payload := map[string]interface{}{
				"msgtype": "markdown",
				"markdown": map[string]string{
					"content": alert_msg,
				},
			}

			jwxmsg, err := json.Marshal(payload)
			//fmt.Println(jwxmsg)
			if err != nil {
				log.Fatal("结构体转json消息出错:", err)
			}
			//body := strings.NewReader(string(jwxmsg))
			payloadBody := bytes.NewReader(jwxmsg)
			rest, err := http.NewRequest("POST", xinwxrl, payloadBody)
			fmt.Println(rest)
			if err != nil {
				log.Fatal("告警消息发送到微信群组出错:", err)
			}
			log.Println("告警发送到企业微信机器人成功:", rest)

			c.JSON(http.StatusOK, gin.H{
				"message": "success",
			})

			client := &http.Client{}
			resp, err := client.Do(rest)
			if err != nil {
				panic(err)
			}
			defer resp.Body.Close()
		}
	})

	fmt.Println("开始启动1999端口")
	r.Run(":1999")

}
